/**
 * 2022年2月18日 13:33:55 chanchaw
 * 制造损失 - 品质异常
 * 1. 快速查找表格列定义：{field: "no", title: "序号", filterable: false, template: "<span class='row_number'></span>", width: 40},
 * 2. 快速查找表格数据源搜索：let grid = $(`#${KENDO_GRID_ID}`).kendoGrid({
 */
const KENDO_GRID_ID = 'v_grid';
const EDIT_FORM_ID = 'form_setBadQty';// 双击表格行弹出的模态窗ID
const URL_SAVE = 'quality/save';
const URL_DATASOURCE_TABLE = 'quality/list';
// const BAD_CTL_ID = ['bad01','bad02','bad03','bad04','bad05','bad06','bad07','bad08',
//     'bad09','bad10','bad11','bad12','bad13','bad14','bad15',
//     'bad16','bad17','bad18','bad19'];
const BAD_CTL_ID = ['bad13','bad14','bad15',
    'bad16','bad17','bad18','bad19'];
const EDIT_DIALOG_WIDTH = 610;
const EDIT_DIALOG_HEIGHT = 530;
let MAINID;
var openwinNumber=0;  //用于判断是否是第一次打开模态窗口

;!(function ($)
{
    $.fn.setFormValue = function (options)
    {
        var $this = $(this);

        $.each(options, function (key, value)
        {
            var obj = $this.find("*[name=" + key + "]");

            if (obj.attr("type") == "checkbox")
            {
                if ($.type(value) === "boolean")
                {
                    obj.attr("checked", value);
                }

                if ($.type(value) === "object")
                {
                    $.each(value, function (i, item)
                    {
                        $this.find("*[name=" + key + "][value=" + i + "]").attr("checked", item);
                    })
                }
            }
            else if (obj.attr("type") == "radio")
            {
                $this.find("*[name=" + key + "][value=" + value + "]").attr("checked", true);
            }
            else
            {
                obj.val(value);
            }
        })
    }

})(jQuery)


$(function () {
    // 初始化页面
    // 1. 两个日期设置默认
    init();
    let buttonGroup = [
        {
            id: 'btn_cancel_add',
            size: 'small',
            text: '新增付款',
            iconCls: 'icon-add',
            plain: true,
            onClick: btn_cancel_add
        },
        {
            id: 'btn_cancel_delete',
            size: 'small',
            text: '删除付款',
            iconCls: 'icon-add',
            plain: true,
            onClick: btn_cancel_delete
        },
        {
            id: 'btn_cancel_filter',
            size: 'small',
            text: '清除过滤',
            iconCls: 'icon-clear',
            plain: true,
            onClick: btn_cancel_filter
        },
        {
            id: 'btn_export',
            size: 'small',
            text: '导出Excel',
            iconCls: 'icon-page_excel',
            plain: true,
            onClick: btn_export_excel
        },
        {
            id: 'btn_grid_columns',
            size: 'small',
            text: '列',
            iconCls: 'icon-text_columns',
            plain: true,
            onClick: btn_open_column_list
        },
        {
            id: 'btn_close', size: 'small', text: '关闭', iconCls: 'icon-no', onClick: btn_close,
            plain: true
        },
    ];
    buttonGen($('#north'), buttonGroup);
    grid_1();
    bindEnterEvents_bp();
    // getedatagrid();

    setcombobox();
})


/*初始化下拉事件*/
function setcombobox(){
    $('#sid').combobox({
        label:'项目：',
        labelAlign:'right',
        url:'jcSimple/listQuery',
        method:'GET',
        textField:'sid',
        valueField:'sid',
        limitToList:true,
        required:true,
        panelHeight:300,
        width:325,
        labelWidth:85,
        onShowPanel:function(){
            $(this).combobox('reload','jcSimple/listQuery');
        },
        loadFilter: function (data) {
            let item = [];
            for (let i = 0; i < data.length; i++) {
                if (data[i].category == '付款项目') item.push(data[i]);
            }
            return item;
        }
    });
    $('#payType').combobox({
        label:'付款类型：',
        labelAlign:'right',
        url:'jcSimple/listQuery',
        method:'GET',
        textField:'sid',
        valueField:'sid',
        limitToList:true,
        required:true,
        panelHeight:300,
        width:325,
        labelWidth:85,
        onShowPanel:function(){
            $(this).combobox('reload','jcSimple/listQuery');
        },
        loadFilter: function (data) {
            let item = [];
            for (let i = 0; i < data.length; i++) {
                if (data[i].category == '付款类型') item.push(data[i]);
            }
            return item;
        }
    });
}

function targetCombo(url) {
    if (url) {
        $('#businessTarget').combobox({
            label:'接收单位：',
            labelAlign:'right',
            url:'jcDyeingFactory/listQuery',
            method:'GET',
            textField:'ctName',
            valueField:'id',
            limitToList:true,
            required:true,
            panelHeight:300,
            width:250,
            onShowPanel:function(){
                $(this).combobox('reload',url);
            }
        });
    } else {
        $('#businessTarget').combobox({
            label:'接收单位：',
            labelAlign:'right',
            data: [{id:0,ctName:'本厂'}],
            textField:'ctName',
            valueField:'id',
            limitToList:true,
            required:true,
            panelHeight:300,
            width:250,
            onShowPanel:function(){
                $(this).combobox('reload',url);
            }
        });
    }
}

function bindEnterEvents_bp() {
    function isIE() {
        return !!window.ActiveXObject || 'ActiveXObject' in window;
    }

    //  获取光标起始索引
    function getCursorIndex(element) {
        if (!isIE()) {
            return element.selectionStart;
        } else {
            let range = element.createTextRange();
            range.moveStart('character', -element.value.length);
            return range.text.length;
        }
    }

    $(document).on('keyup', 'input[type!="hidden"][readonly!="readonly"]:visible', function (e) {
        let inputs = $('input[type != "hidden"][readonly != "readonly"]:visible');
        let length = inputs.length;
        let currentIndex = inputs.index($(this));
        if (e.keyCode == 13) {
            if (length - 2 >= currentIndex) {
                inputs.eq(currentIndex + 1).focus();
            }
        } else if (e.keyCode == 37) {
            //  左箭头
            if (currentIndex - 1 >= 0) {
                if (getCursorIndex(this) === 0)
                    inputs.eq(currentIndex - 1).focus();
            }
        } else if (e.keyCode == 39) {
            //  右箭头
            if (length - 2 >= currentIndex) {
                if (getCursorIndex(this) >= $(this).val().length)
                    inputs.eq(currentIndex + 1).focus();
            }
        }
    })
}

function grid_1() {
    let SUFFIX = "";
    let billDate = new kendo.data.DataSource({data: []});
    let client = new kendo.data.DataSource({data: []});
    let sid = new kendo.data.DataSource({data: []});
    let payType = new kendo.data.DataSource({data: []});
    let remark = new kendo.data.DataSource({data: []});

    let halfName = new kendo.data.DataSource({data: []});
    let halfSpecification = new kendo.data.DataSource({data: []});
    let color = new kendo.data.DataSource({data: []});

    let dataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "payment/selectDeepMeet",
                dataType: "json",
                type: "GET",
                data: {
                    sdate: $('#start').datebox('getValue'),
                    edate: $('#end').datebox('getValue'),
                    client: $('#client').combobox('getValue'),
                    value: 1
                }
            }
        },
        schema: {
            model: {
                id: 'id',
                fields: {
                    piece: {type: "number"},
                    kilo: {type: "number"},
                    meter: {type: "number"},
                    price: {type: "number"},
                    money: {type: "number"},
                    ticketMoney: {type: "number"},
                }
            }
        },
        aggregate: [
            {field: "piece", aggregate: "sum"},
            {field: "kilo", aggregate: "sum"},
            {field: "meter", aggregate: "sum"},
            {field: "money", aggregate: "sum"},
            {field: "ticketMoney", aggregate: "sum"},

        ],
        change: function (e) {
            //获取过滤条件
            let filtrer = this.filter();
            //获取所有数据
            let allData = this.data();
            //进行过滤条件的筛选
            let query = new kendo.data.Query(allData);
            //获取过过滤后的数据
            let data = query.filter(filtrer).data;

            // mainId.data(unique(data, 'mainId'));
            // detailId.data(unique(data, 'detailId'));
            billDate.data(unique(data, 'billDate'));
            client.data(unique(data, 'client'));
            remark.data(unique(data, 'remark'));
            sid.data(unique(data, 'sid'));

            halfName.data(unique(data, 'halfName'));
            halfSpecification.data(unique(data, 'halfSpecification'));
            color.data(unique(data, 'color'));
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('disable')
                }
            })
            $('body').find('th a[class="k-grid-filter"]').css({display: 'none'});
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('enable')
                }
            })
            $('body').find('th a[class="k-grid-filter"]').css({display: 'none'});
        }
    });
    let columns = [
        {field: "no", title: "序号", filterable: false, template: "<span class='row_number'></span>", width: 40},
        {
            field: "billDate",
            title: '单据日期',
            width: 95,
            format: "{0: yyyy-MM-dd}",
            filterable: {multi: true, search: true, dataSource: billDate},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "sid",
            title: '项目',
            width: 95,
            filterable: {multi: true, search: true, dataSource: sid},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "payType",
            title: '付款类型',
            width: 95,
            filterable: {multi: true, search: true},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "client",
            title: '深加工',
            width: 95,
            filterable: {multi: true, search: true, dataSource: client},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "halfName",
            title: '品名',
            width: 95,
            filterable: {multi: true, search: true, dataSource: halfName},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "halfSpecification",
            title: '规格',
            width: 95,
            filterable: {multi: true, search: true, dataSource: halfSpecification},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "color",
            title: '颜色',
            width: 95,
            filterable: {multi: true, search: true, dataSource: color},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'piece',
            title: '匹数',
            width: 70,
            template: item => {
                return item.piece ? parseFloat(item.piece).toFixed(0) : '';
            },
            footerTemplate: '#=kendo.format("{0:n0}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            format: "{0:n0}",
            filterable: false,
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'kilo',
            title: '公斤',
            width: 70,
            template: item => {
                return item.kilo ? parseFloat(item.kilo).toFixed(1) : '';
            },
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            format: "{0:n0}",
            filterable: false,
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'meter',
            title: '米数',
            width: 70,
            template: item => {
                return item.meter ? parseFloat(item.meter).toFixed(1) : '';
            },
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            format: "{0:n0}",
            filterable: false,
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'price',
            title: '单价',
            width: 70,
            template: item => {
                return item.price ? parseFloat(item.price).toFixed(2) : '';
            },
            footerAttributes: {style: 'text-align:right;'},
            format: "{0:n0}",
            filterable: false,
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'money',
            title: '金额',
            width: 70,
            template: item => {
                return item.money ? parseFloat(item.money).toFixed(2) : '';
            },
            footerTemplate: '#=kendo.format("{0:n2}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            format: "{0:n0}",
            filterable: false,
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'ticketMoney',
            title: '开票金额',
            width: 70,
            template: item => {
                return item.ticketMoney ? parseFloat(item.ticketMoney).toFixed(2) : '';
            },
            footerTemplate: '#=kendo.format("{0:n2}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            format: "{0:n0}",
            filterable: false,
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: "remark",
            title: '备注',
            width: 150,
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
        },
    ];
    let grid = $(`#${KENDO_GRID_ID}`).kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: {
            extra: false
        },
        dataSource: dataSource,
        columnMenu: false,
        excel: {
            fileName: "深加工应付款.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        height: '99%',
        pageable: {
            pageSize: 200
        },
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });

            changeBackgroundColor();
        },
        columnHide: function (e) {
            //列隐藏事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, true, null);
        },
        columnShow: function (e) {
            //列显示事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, false, null);
        },
        columnResize: function (e) {
            //  列伸缩事件
            let field = e.column.field;
            let newWidth = e.newWidth;
            if (newWidth < 20) {
                columnResizeEvent($('body').data('menu_id'), field, null, true, null);
            } else {
                columnResizeEvent($('body').data('menu_id'), field, newWidth, null, null);
            }
        },
        columnReorder: function (e) {
            //  列拖动事件
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex);
            let menuId = $('body').data('menu_id');
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNum: i,
                        sysMenuId: menuId,
                        field: newColumns[i]['field']
                    });
            }
            $.ajax({
                url: 'sysUserTableConfig/modify/reorder',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    let grid01 = $('#v_grid').data('kendoGrid');
    loadOptions(grid01, columns, SUFFIX, $('body').data('menu_id'));
    $('body').on('mouseenter', 'th', function (e) {
        $('.k-grid-filter').finish();
        $(this).find('.k-grid-filter').fadeIn();
    })
    $('body').on('mouseleave', 'th', function (e) {
        $(this).find('.k-grid-filter').fadeOut();
    })
    grid.on('dblclick', 'tr', function (e) {
        //  双击打开原单
        let kGrid = $("#v_grid").data("kendoGrid");
        let dataItem = kGrid.dataItem(e.currentTarget);
        let id = dataItem.id;
        if (dataItem.sid == '期初数据' || dataItem.payType == '深加工入库' || dataItem.payType == '退货深加工') return;
        MAINID = id;
        openwinNumber=1
        $('#order_log').dialog('open');
        // setStatus(dataItem.state);
        queryLog(id);
    });
}

//开关
// function finishedOrAll() {
//     let value = $('#btn_finishedOrAll').switchbutton('options').checked;
//     if (value) {
//         $('#start').datebox('enable');
//         $('#end').datebox('enable');
//         btn_search();
//     } else {
//         $('#start').datebox('disable');
//         $('#end').datebox('disable');
//         btn_search(2);
//     }
// }

//查询单据
function queryLog(id) {
    $.ajax({
        url: 'payment/queryByPk/' + id,
        contentType: 'application/json',
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            if (data) {
                $('#billDate').datebox('setValue',data.billDate);
                $('#clientId').combobox('setValue',data.clientId);
                $('#sid').combobox('setValue',data.sid);
                $('#money').numberbox('setValue',data.money);
                $('#payType').combobox('setValue',data.payType);
                $('#remark').textbox('setValue',data.remark);
                $('#btn_delete').linkbutton('enable');
                openwinNumber=0
            } else {
                $.messager.alert('警告', '未查询到数据!', 'warning');
                $('#order_log').dialog('close');
                MAINID = null;
                openwinNumber=0
            }
        }
    })
}

/*============================================= 单据模态窗 ================================================*/

let ORDERNO = '';

function formatter(value, row, index) {
    return value ? parseFloat(value).toFixed(1) : null;
}

//选择单据类型，填充数据
function typeByBusinessSource() {
    let billType = $('#billType').combobox('getValue');
    if (billType == '白坯直发染厂') $('#businessTarget').combobox('setValue', 1)
}


function shipPay_loadFilter(data) {
    let item = [];
    for (let i = 0; i < data.length; i++) {
        if (data[i].storageId == '运费付费方') item.push(data[i]);
    }
    return item;
}

// 保存
function btn_saveData() {
    let url;
    if (MAINID) url = 'payment/updateSelective';
    else url = 'payment/insertSelectiveDeep';
    let record = {
        id: MAINID,
        state: STATUS == 0 ? 1 : STATUS,
        billDate: $('#billDate').datebox('getValue'),
        clientId: $('#clientId').combobox('getValue'),
        sid: $('#sid').combobox('getValue'),
        money: $('#money').numberbox('getValue'),
        payType: $('#payType').combobox('getValue'),
        remark: $('#remark').textbox('getValue')
    }
    if (!record.billDate) {
        $.messager.alert('警告', '日期不允许为空!', 'warning');
        return;
    }
    if (!record.clientId) {
        $.messager.alert('警告', '深加工不允许为空!', 'warning');
        return;
    }
    if (!record.sid) {
        $.messager.alert('警告', '项目不允许为空!', 'warning');
        return;
    }
    if (!record.money) {
        $.messager.alert('警告', '金额不允许为空!', 'warning');
        return;
    }
    if (!record.payType) {
        $.messager.alert('警告', '收款类型不允许为空!', 'warning');
        return;
    }
    $.ajax({
        url: url,
        contentType: 'application/json',
        data: JSON.stringify(record),
        type: 'post',
        dataType: 'json',
        success: function (data) {
            console.log(data);
            if (data.success){
                btn_search();
                if (STATUS == 0) STATUS = 1;
                else STATUS = data.state;
                // MAINID = data.id;
                // setStatus(STATUS);
                // btn_close_log();
                clear_log();
                $('#order_log').dialog('close');
                btn_search(1);
                // queryLog(MAINID);
                $.messager.show({title: '提示', msg: '成功'});
            } else {
                $.messager.show({title: '提示', msg: data.message});
            }
        }
    })
}

function btn_delete() {
    if (MAINID) {
        $.ajax({
            url: 'payment/deleteByPrimaryKey/' + MAINID,
            contentType: 'application/json',
            type: 'GET',
            success: function (data) {
                if (data.success) {
                    clear_log();
                    btn_search(1);
                    $('#order_log').dialog('close');
                    $.messager.show({title: '提示', msg: '成功'});
                    openwinNumber=0
                } else {
                    $.messager.alert('警告', data.messages, 'warning');
                    openwinNumber=0
                }
            }
        })
    }
}

let STATUS = 0;

/*function setStatus(s) {
    STATUS = s;
    switch (s) {
        case 0://修改状态
            enableFormAllControl($("#form"));
            $('#img_state').addClass('hidden');
            $('#img_state_01').addClass('hidden');
            $(".easyui-linkbutton").each(function () {
                if ($(this).attr("id") == "btn_addBill" ||
                    $(this).attr("id") == "btn_billOk" ||
                    $(this).attr("id") == "btn_deleteBill" ||
                    $(this).attr("id") == "btn_billNo" ||
                    $(this).attr("id") == "btn_copyBill" ||
                    $(this).attr("id") == 'btn_updateData') {
                    $(this).linkbutton("disable");
                } else {
                    $(this).linkbutton("enable");
                }
            });
            break;
        case 1://已保存状态
            disableFormAllControl($("#form"));
            $('#img_state').removeClass('img-delete img-audit img-cancel hidden');
            $('#img_state_01').addClass('hidden');
            $('#img_state').addClass('img-save');
            $(".easyui-linkbutton").each(function () {
                if ($(this).attr("id") == "btn_addRow" ||
                    $(this).attr("id") == "btn_saveData" ||
                    $(this).attr("id") == "btn_copyRow" ||
                    $(this).attr("id") == "showTechModal" ||
                    $(this).attr("id") == "btn_delectRow" ||
                    $(this).attr("id") == "btn_billNo") {
                    $(this).linkbutton("disable");
                } else {
                    $(this).linkbutton("enable");
                }
            });
            break;
        case 2://已完成状态
            disableFormAllControl($("#form"));
            $('#img_state').removeClass('img-delete img-audit img-cancel hidden');
            $('#img_state_01').removeClass('img-delete img-audit img-cancel hidden');
            $('#img_state').addClass('img-save');
            $('#img_state_01').addClass('img_finished');
            $(".easyui-linkbutton").each(function () {
                if ($(this).attr("id") == "btn_addBill" ||
                    $(this).attr("id") == "btn_addRow" ||
                    $(this).attr("id") == "btn_updateData" ||
                    $(this).attr("id") == "btn_copyBill" ||
                    $(this).attr("id") == "btn_deleteBill" ||
                    $(this).attr("id") == "btn_saveData" ||
                    $(this).attr("id") == "btn_copyRow" ||
                    $(this).attr("id") == "btn_delectRow" ||
                    $(this).attr("id") == "btn_billOk" ||
                    $(this).attr("id") == 'btn_copyBill') {
                    $(this).linkbutton("disable");
                } else {
                    $(this).linkbutton("enable");
                }
            });
            break;
        // case '3':
        //     $('#img_state').removeClass('img-delete img-audit img-save hidden');
        //     $('#img_state').addClass('img-cancel');
        //     $('#e_grid').edatagrid('disableEditing');
        //     disableFormEdit($('#form'))
        //     $('#btn_group .easyui-linkbutton').each(function () {
        //         let title = $(this).linkbutton('options').text;
        //         if (['新增单据', '上张', '下张', '关闭'].indexOf(title) >= 0) {
        //             $(this).linkbutton('enable');
        //         } else {
        //             $(this).linkbutton('disable');
        //         }
        //     })
        //     break;
    }
}*/

//新增单据
function btn_addBill() {
    // setStatus(0);
    clear_log();
}

//模态窗-删除单据
function btn_deleteBill() {
    $.messager.confirm('确认', '确定删除本单据吗？不可恢复！', function (r) {
        if (r) {
            var ids = [];
            ids.push(MAINID);
            $.ajax({
                url: 'payment/deleteByIds',
                contentType: 'application/json',
                data: JSON.stringify(ids),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                    console.log(data);
                    btn_close_log();
                    btn_search();
                }
            })
        }
    })
}

function btn_updateData(){
    // setStatus(0)
}

//订单完成
function btn_billOk() {
    // setStatus(2);
    btn_saveData();
}

//订单取消完成
function btn_billNo() {
    // setStatus(1);
    btn_saveData();
}

//关闭模态窗
function btn_close_log() {
    if ($('#clientId').combobox('getValue') ||
        $('#sid').combobox('getValue') ||
        $('#money').numberbox('getValue') ||
        $('#remark').textbox('getValue') ||
        $('#payType').combobox('getValue')) {
        $.messager.confirm('确认', '操作未保存，确定继续退出吗？', function (r) {
            if (r) {
                clear_log();
                $('#order_log').dialog('close');
            }
        })
    }else {
        clear_log();
        $('#order_log').dialog('close');
    }
}

//清空模态窗所有内容
function clear_log() {
    $('#billDate').datebox('setValue', getCurrentDate());
    $('#clientId').combobox('clear');
    $('#sid').combobox('clear');
    $('#money').numberbox('clear');
    $('#payType').combobox('clear');
    $('#remark').textbox('clear');
    MAINID = null;
    ORDERNO = null;
}

//订单工艺选择模态窗
function showTechModal() {
    $('#techModal').dialog('open');
}

function loadTechOptions() {
    // 清空原有内容
    $('#techOptionsContainer').empty().html('加载中...');

    // 发送AJAX请求获取数据（示例使用jQuery）
    $.ajax({
        url: 'jcSimple/listQuery',  // 替换为你的真实接口地址
        method: 'GET',
        success: function(response) {
            // 清空容器
            $('#techOptionsContainer').empty();

            let item = []
            for (let i = 0; i < response.length; i++) {
                if (response[i].category == '深加工工艺') item.push({value: response[i].sid, name: response[i].sid});
            }
            // 遍历数据创建选项
            item.forEach(function(tech) {
                const label = $('<label>').addClass('option-item');
                const input = $('<input>', {
                    type: 'checkbox',
                    name: 'techOption',
                    value: tech.value,
                    style: 'transform:scale(1.3); margin-right:8px;'
                });

                // 组合元素
                label.append(input).append(document.createTextNode(' ' + tech.name));
                $('#techOptionsContainer').append(label).append('<br>');
            });
        },
        error: function() {
            // 错误处理
            $('#techOptionsContainer').empty().html('加载失败');
            $.messager.alert('错误', '工艺数据加载失败，请重试！');
        }
    });
}

// 确认选择
function confirmTechSelection() {
    var selected = [];
    $('input[name="techOption"]:checked').each(function() {
        selected.push($(this).val());
    });

    $('#craftRemark').textbox('setValue', selected.join(', '));
    $('#techModal').dialog('close');
}

/*========================================================================================================*/

function btn_cancel_add() {
    $('#order_log').dialog('open');
    // setStatus(0)
    clear_log();
}

//序时表-删除单据
function btn_cancel_delete() {
    let kGrid = $("#v_grid").data("kendoGrid");
    // 获取当前选中行
    var selectedRow = kGrid.select();
    // 获取选中行的数据项
    var selectedData = kGrid.dataItem(selectedRow);
    let id = selectedData.id;
    if (selectedData.payType == '期初数据' || selectedData.payType == '坯布入库' || selectedData.payType == '坯布退货') return;
    MAINID = id;
    openwinNumber=1
    $('#order_log').dialog('open');
    // setStatus(selectedData.state);
    queryLog(id);
}

/** 禁用Easyui form中的所有组件*/
function disableFormAllControl(ff) {
    $("input[textboxname]", ff).each(function (i, n) {
        $(n).textbox('disable');
    });
    $("input[comboboxname]", ff).each(function (i, n) {
        $(n).textbox('disable');
    });
    $("input[switchbuttonname]", ff).each(function (i, n) {
        $(n).switchbutton('disable');
    });
    $(".easyui-linkbutton", ff).each(function (i, n) {
        $(n).linkbutton('disable');
    });
}

/** 启用Easyui form中的所有组件*/
function enableFormAllControl(ff) {
    $("input[textboxname]", ff).each(function (i, n) {
        $(n).textbox('enable');
    });
    $("input[comboboxname]", ff).each(function (i, n) {
        $(n).textbox('enable');
    });
    $("input[switchbuttonname]", ff).each(function (i, n) {
        $(n).switchbutton('enable');
    });
    $(".easyui-linkbutton", ff).each(function (i, n) {
        $(n).linkbutton('enable');
    });
}

function btn_cancel_filter() {
    $('#v_grid').data('kendoGrid').dataSource.filter({});
}

function btn_search(flag) {
    if (!flag) flag = 1;
    $('#v_grid').data('kendoGrid').dataSource.read({
        sdate: $('#start').datebox('getValue'),
        edate: $('#end').datebox('getValue'),
        client: $('#client').combobox('getValue'),
        flag: flag
    })
}

function btn_open_column_list() {
    let kendoGridID = '#v_grid';
    let options = $(kendoGridID).data('kendoGrid').getOptions().columns;
    if ($('#btn_open_column_list').length <= 0) {
        let div = $(`<div data-options="resizable:true,iconCls:'icon-text_columns',width:200,height:300,modal:true,title:'列'" 
                          class="easyui-dialog" id="btn_open_column_list">
                   </div>`);
        let form = $('<form style="width: 100%;height: 100%;"></form>')
        for (let i of options) {
            if (i.field) {
                let checkbox = $(`<div style="width: 100%;height: auto;padding: 5px;">
                <input class="easyui-checkbox" name="${i.field}" data-options="label:'${i.title}',
                labelWidth:120,value:true,name:'${i.field}'">
                </div>`);
                form.append(checkbox);
            }
        }
        let container = $(`<div></div>`);
        form.appendTo(div);
        div.appendTo(container);
        $('body').append(container);
        $.parser.parse($('#btn_open_column_list').parent());
        let formData = {};
        options.map(item => {
            formData[item['field']] = item['hidden'] == undefined ? true : !item['hidden'];
        })
        $('#btn_open_column_list form').eq(0).form('load', formData);
        $('#btn_open_column_list form .easyui-checkbox').each(function () {
            //  绑定事件
            $(this).checkbox({
                onChange: function (checked) {
                    let opts = $(this).checkbox('options');
                    if (checked) {
                        $(kendoGridID).data('kendoGrid').showColumn(opts.name);
                    } else {
                        $(kendoGridID).data('kendoGrid').hideColumn(opts.name);
                    }
                }
            })
        })
    } else {
        $('#btn_open_column_list').dialog('open');
    }
}

//  打印
function btn_print() {
    let start = $('#start').datebox('getValue');
    let end = $('#end').datebox('getValue');
    let storageId = $('#storageId').combobox('getValue');
    if (!start || !end || !storageId) {
        $.messager.alert('提示', '请选择日期和仓库', 'warning');
        return;
    }
    window.parent.FR.doURLPDFPrint({
        url: $(window.parent.document.body).data('report_url'),
        isPopUp: false,
        data: {
            reportlets: [{
                reportlet: '材料收发存汇总.cpt',
                start: start,
                end: end,
                storageId: storageId
            }]
        }
    });
}

function btn_export_excel() {
    $('#v_grid').data('kendoGrid').saveAsExcel();
}

function btn_close() {
    window.parent.closeTab();
}

/*function createEditDialog(){
    // left:0,top:0
    let divElement = `
   <div id="editDialog" class="easyui-dialog" data-options="closed:true,">
    <form id="form_setBadQty" style="width: 100%;height: 100%;">
        <div class="easyui-layout" data-options="fit:true">
            <div id="west" data-options="region:'west',split:false" title="基础信息" style="width:300px;">
                <div class="input-group">
                    <input type="hidden"  id="iid" name="iid" >
                    <input type="hidden"  id="product_plan_dtl_id" name="product_plan_dtl_id">
                    <input type="hidden"  id="contact_company_id" name="contact_company_id">
                </div>

                <table id="table01" style="width: 100%">
                    <tr>
                    <td><input type="hidden"  id="material_order_bill_dtl_id" name="material_order_bill_dtl_id" /></td><!-- 材料明细主键 -->
                    <td><input type="hidden"  id="product_order_bill_dtl_id" name="product_order_bill_dtl_id" /></td>  <!-- 成品明细主键 -->
                    </tr>
                    <tr>
                        <td><input class="easyui-textbox" id="in_date" name="in_date" data-options="labelWidth:'100px',label:'生产入库日期：', labelAlign:'right', readonly:true," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input class="easyui-textbox" id="order_code" name="order_code" data-options="labelWidth:'100px',label:'订单号：', labelAlign:'right', readonly:true," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input class="easyui-textbox" id="ct_name" name="ct_name" data-options="labelWidth:'100px',label:'客户：', labelAlign:'right', readonly:true," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input class="easyui-textbox" id="product_coded" name="product_coded" data-options="labelWidth:'100px',label:'存货编码：', labelAlign:'right', readonly:true," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input class="easyui-textbox" id="pf_name" name="pf_name" data-options="labelWidth:'100px',label:'存货名称：', labelAlign:'right', readonly:true," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input class="easyui-numberbox" id="plan_qty" name="plan_qty" data-options="labelWidth:'100px',
                            label:'生产计划数量：', labelAlign:'right', readonly:true," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input class="easyui-numberbox" id="qty_total" name="qty_total" data-options="labelWidth:'100px',onChange:function(){ updateGoodsQty() },
                            label:'过机数量：', labelAlign:'right', readonly:false," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input class="easyui-numberbox" id="qty_good" name="qty_good" data-options="labelWidth:'100px',label:'良品数：', labelAlign:'right', readonly:false," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input class="easyui-numberbox" id="qty_bad" name="qty_bad" data-options="labelWidth:'100px',label:'不良数：', labelAlign:'right', readonly:false," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input class="easyui-textbox" id="project_sid" name="project_sid" data-options="labelWidth:'100px',label:'工程：', labelAlign:'right', readonly:true," style="width: 100%"></td>
                    </tr>
                </table>
            </div>

<!--            <div data-options="region:'center',split:false" title="不良原因1">-->
<!--                <table id="table02" style="width: 100%">-->
<!--                    <tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad01" name="bad01" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'纸板不良：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                    <tr>-->
<!--                    </tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad02" name="bad02" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'试机：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                    </tr>-->
<!--    -->
<!--                    <tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad03" name="bad03" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'投纸破损：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                    <tr>-->
<!--                    </tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad04" name="bad04" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'进纸跑位：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                    </tr>-->
<!--    -->
<!--                    <tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad05" name="bad05" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'里纸过机：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                                            <tr>-->
<!--                    </tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad06" name="bad06" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'印刷露白：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                    </tr>-->
<!--    -->
<!--                    <tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad07" name="bad07" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'印刷漏印、缺印：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                    <tr>-->
<!--                    </tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad08" name="bad08" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'印刷溢墨、重影、不匀：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                    </tr>-->
<!--    -->
<!--                    <tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad09" name="bad09" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'爆线：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                    <tr>-->
<!--                    </tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad10" name="bad10" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'废纸压伤，破损：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                    </tr>-->
<!--    -->
<!--                    <tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad11" name="bad11" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'生产过程脏污、破损、折痕：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                    <tr>-->
<!--                    </tr>-->
<!--                        <td><input  class="easyui-numberbox" id="bad12" name="bad12" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'230px',label:'糊箱不良（错位，内连，脱胶）：', labelAlign:'right', readonly:false," style="width: 100%"></td>-->
<!--                    </tr>-->
<!--                </table>-->
<!--            </div>-->

            <div data-options="region:'center',split:false" title="不良原因" style="width:150px;">
                <table id="table03" style="width: 100%">
                    <tr>
                        <td><input  class="easyui-numberbox" id="bad13" name="bad13" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'160px',label:'强度不良：', labelAlign:'right', readonly:false," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input  class="easyui-numberbox" id="bad14" name="bad14" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'160px',label:'模切不良：', labelAlign:'right', readonly:false," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input  class="easyui-numberbox" id="bad15" name="bad15" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'160px',label:'成形 使用不能：', labelAlign:'right', readonly:false," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input  class="easyui-numberbox" id="bad16" name="bad16" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'160px',label:'印刷不良：', labelAlign:'right', readonly:false," style="width: 100%"></td>
                    </tr>
                
                    <tr>
                        <td><input  class="easyui-numberbox" id="bad17" name="bad17" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'160px',label:'脏污.破损.折痕：', labelAlign:'right', readonly:false," style="width: 100%"></td>
                    </tr>
                    <tr>
                        <td><input  class="easyui-numberbox" id="bad18" name="bad18" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'160px',label:'粘合不良：', labelAlign:'right', readonly:false," style="width: 100%"></td>
                    </tr>
                
                    <tr>
                        <td><input  class="easyui-numberbox" id="bad19" name="bad19" data-options="onChange:function(e){ updateBadQty(e) },labelWidth:'160px',label:'其他：', labelAlign:'right', readonly:false," style="width: 100%"></td>
                    <tr>

                    <tr>
                        <td><input  class="easyui-numberbox" id="bad_money" name="bad_money" data-options="labelWidth:'160px',label:'不良损失金额：', labelAlign:'right',precision:2,readonly:true," style="width: 100%"></td>
                    </tr>
                
                    <tr>
                        <td align="right" style="padding-right: 110px">
                        <input id="bad_source_mill" name="bad_source_mill" class="easyui-checkbox" data-options="label:'不良原因-厂家：',labelWidth:100,labelPosition:'before',value:true,checked:false">
                        </td>
                    <tr>
                    </tr>
                        <td align="right" style="padding-right: 110px">
                        <input id="bad_source_project" name="bad_source_project" class="easyui-checkbox" data-options="label:'不良原因-工程内：',labelWidth:110,labelPosition:'before',value:true,checked:false">
                        </td>
                    </tr>
                    <tr>
                        <td><input type="hidden"  id="sales_price_withtax" name="sales_price_withtax" class="easyui-numberbox" data-options="precision:2"></td>
                    </tr>
                    <tr>
                        <td><input type="hidden"  id="sales_price_nottax" name="sales_price_nottax" class="easyui-numberbox" data-options="precision:2"></td>
                    </tr>
                    
                </table>
            </div>
        </div>
    </form>
</div>
`;

    // 2022年3月2日 21:58:28 将弹出模态窗中的该元素取消，在“不良损失金额”上面，“其他”下面
// </tr>
//     <td><input id="sales_price_withtax" name="sales_price_withtax" class="easyui-numberbox" data-options="label:'含税销售单价',precision:2" ></td>
//         </tr>
//         </tr>
//         <td><input id="sales_price_nottax" name="sales_price_nottax" class="easyui-numberbox" data-options="label:'不含税销售单价',precision:2"></td>
//         </tr>

    if ($('#editDialog').length <= 0) {
        $(divElement).appendTo($('body'));

        // 创建对话框后绑定事件
        //bindEvent_BadQtyCtl_batch();
    }

}*/

// 设置不良数量
function saveBadQty(){
    if( !check4Save() ) return;// 检查不合法则退出不保存
    const formData = serializeObject('form_setBadQty');
    console.log(formData);

    $.ajax({
        type : "POST",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(formData),
        url : URL_SAVE,
        success : function(res) {
            if(!res.success){
                msg(res.message);
                return
            }

            msg('保存成功');
            $(`#editDialog`).dialog({closed: true});
            refreshGrid();// 刷新表格
        },
        error : function(e){
            console.log(e.status);
            console.log(e.responseText);
        },
        complete: function () {
            // 旭纸业项目中通过 progress 锁定前端页面
            // $.messager.progress({title: '提示', text: '请稍候...', interval: 5000});
            // $.messager.progress('close');
        }
    })
}

// 初始化编辑用模态窗的数据 - 填充订单号、客户、存货编码等信息
/*function initEditDialog(){
    const selectedRows = getKendoGridSelectedRowData(KENDO_GRID_ID);
    if( !selectedRows || selectedRows.length <=0 ){
        $.messager.show({title: '提示', msg: '选中一行后再执行本操作！'});
        return false;
    }

    // createEditDialog();// 先创建对话框

    const rowData = selectedRows[0];

    const formatedDate = new Date(rowData.in_date).format('yyyy-MM-dd');

    // 通过自定义方法给表单赋值
    // 该方法在打开对话框时会显示上一次的数据，关闭再次打开才会显示最新的数据
    // $(`#form_setBadQty`).setFormValue(rowData);
    // $(`#form_setBadQty`).setFormValue({
    //     in_date: formatedDate
    // });

    // 通过 load 方法给表单赋值
    rowData.in_date = formatedDate;
    $(`#form_setBadQty`).form('load',rowData);

    setTimeout(() => {
        updateBadQty();// 更新不良汇总数量
    },100);

    const sourceMill = rowData.bad_source_mill || false;
    const sourceProject = rowData.bad_source_project || false;
    $('#bad_source_mill').checkbox({checked:sourceMill});
    $('#bad_source_project').checkbox({checked:sourceProject});

    return true;
}*/

function serializeObject(formId) { /*将form表单内的元素序列化为对象，扩展Jquery的一个方法*/
    let o = {};
    let form = $(`#${formId}`);
    $.each(form.serializeArray(), function (index) {
        if (o[this['name']]) {
            o[this['name']] = o[this['name']] + "," + this['value'];
        } else {
            o[this['name']] = this['value'];
        }
    });
    return o;
}

// 2022年2月20日 08:29:40 chanchaw
// 保存前调用本方法检查当前数据是否合法，合法则返回 true，相反则返回 false，调用方不继续保存数据
// 检查内容如下：
// 1. 过机数 = 良品数 + 不良数
function check4Save(){
    const formData = serializeObject(EDIT_FORM_ID);
    if(!check4Save_qtyTotal(formData)) return false;

    return true;
}

// 检测：过机数 = 良品数量 + 不良数量
// 不等则返回 false
function check4Save_qtyTotal(formData){
    if( !formData ) return true;
    const qtyTotal = formData.qty_total || 0;
    const qtyGoods = formData.qty_good || 0;
    const qtyBad = formData.qty_bad || 0;

    const total = parseFloat(qtyTotal);
    const a = parseFloat(qtyGoods);
    const b = parseFloat(qtyBad);
    const total1 = a+b;

    if( total !== total1 ){
        msg('过机数 = 良品数 + 不良数。请检查数量设置是否正确！');
        return false;
    }

    return true;
}

// 不良原因控件 onChange 事件触发，传入参数是当前控件的最新值
function updateBadQty(currentVal){
    let sum1 = 0;
    for (let i = 0; i < BAD_CTL_ID.length; i++) {
        const val = $(`#${BAD_CTL_ID[i]}`).numberbox('getValue') || 0;
        sum1 += convert2Float(val);
    }
    $('#qty_bad').numberbox('setValue',sum1);

    // 不良数量有变动则同时更新良品数量
    updateGoodsQty();

    // 同时更新损失金额
    const priceWithTax = $('#sales_price_withtax').numberbox('getValue') || 0;
    const priceNoTax = $('#sales_price_nottax').numberbox('getValue') || 0;
    const moneyWithTax = priceWithTax * sum1;
    const moneyNoTax = priceNoTax * sum1;
    $('#bad_money').numberbox('setValue',moneyWithTax > 0 ? moneyWithTax : moneyNoTax || 0);
}

// 更新良品数量 = 过机数量 - 不良数量
function updateGoodsQty(){
    const qtyTotal = convert2Float($('#qty_total').numberbox('getValue') || 0);
    const qtyBad = convert2Float($('#qty_bad').numberbox('getValue') || 0);
    const qtyGoods = convert2Float(qtyTotal - qtyBad);
    $('#qty_good').numberbox('setValue',qtyGoods);
}


// 刷新表格
function refreshGrid(){
    $('#flag').checkbox('uncheck');
    $(`#${KENDO_GRID_ID}`).data("kendoGrid").dataSource.read({
        sdate: $('#start').datebox('getValue'),
        edate: $('#end').datebox('getValue'),
        flag: 0
    });
}

// 2022年2月21日 16:32:31 chanchaw
// 批量绑定事件会导致中间栏 input 宽度最小
// 之后弃用该方法
function bindEvent_BadQtyCtl_batch(){
    for (let i = 0; i < BAD_CTL_ID.length; i++) {
        $(`#${BAD_CTL_ID[i]}`).numberbox({
            onChange: function(newVal,oldVal){
                //updateBadQty(newVal,oldVal);
            }
        });
    }

    // 过机数量修改后及时刷新良品数量
    $('#qtyTotal').numberbox({
        onChange: function(newVal,oldVal){
            updateGoodsQty();
        }
    });

    // 不良数量修改后及时刷新良品数量
    $('#qtyBad').numberbox({
        onChange: function(newVal,oldVal){
            updateGoodsQty();
        }
    });
}

// 行变色
function changeBackgroundColor(){
    let kGrid = $('#v_grid').data('kendoGrid');
    let gridRows = kGrid.tbody.find("tr");

    for(let i=0;i<gridRows.length;i++){
        const rowData = kGrid.dataItem(gridRows[i]);
        const mainState = rowData.mainState;

        if( mainState == 2){
            // $(gridRows[i]).css("background-color", "blue"); // 修改背景颜色
            $(gridRows[i]).css("color", "blue"); // 修改颜色
        }
        // if( main_state == 0){
        //     // $(gridRows[i]).css("background-color", "blue"); // 修改背景颜色
        //     $(gridRows[i]).css("color", "red"); // 修改颜色
        // }
    }

}

function checkModifyPermission(){
    let ret = true;
    $.ajax({
        async: false,
        type : "GET",
        contentType: "application/json;charset=UTF-8",
        url : "quality/modify", // 验证是否有修改权限的后台API
        success : function(result) {
            if( !result.success ){
                messageAlertError('没有权限进行该操作！');
                ret = false;
            }
        },
        error : function(e){
            console.log(e.status);
            console.log(e.responseText);
        },
        complete: function () {
            // 旭纸业项目中通过 progress 锁定前端页面
            // $.messager.progress({title: '提示', text: '请稍候...', interval: 5000});
            // $.messager.progress('close');
        }
    })

    return ret;
}

// 初始化页面
function init(){
    const firstDay = curMonthFirstDay();
    const today = dateToStr('yyyy-MM-dd',new Date());
    const firstDayString = dateToStr('yyyy-MM-dd',firstDay);
    // $('#start').datebox('setValue',firstDayString);
    // $('#end').datebox('setValue',today);

    // 初始化右键菜单
    initContextMenu();
}

// 初始化右键菜单
function initContextMenu(){
    $(document).bind('contextmenu', function (e) {
        e.preventDefault();
        $('#mm').menu('show', {
            left: e.pageX,
            top: e.pageY
        });
    });
}

// 拷贝当前行数据到粘贴板
function copyRowData(){
    let selectedRows = getSelectedRows();
    if (!selectedRows) {
        msg("选中行后再执行本操作！")
        return
    }

    let codedString = "";
    selectedRows.each(function (index, item) {
        let dataItem = $('#v_grid').data('kendoGrid').dataItem($(this));
        codedString = codedString + JSON.stringify(dataItem) + ",";
    })

    // 移除最后一个符号
    codedString = removeSuffix(codedString, ",");
    copyToClip(codedString);
    codedString.length > 0 ? $.messager.show({title: '提示', msg: '复制完毕！'}) : $.messager.show({
        title: '提示',
        msg: '复制了空白内容！'
    })
}

// 拷贝选中行的存货编码到剪贴板 - 可选中多行
function copyCoded() {
    let selectedRows = getSelectedRows();
    if (!selectedRows) {
        msg("选中行后再执行本操作！")
        return
    }
    let codedString = "";
    selectedRows.each(function (index, item) {
        let dataItem = $('#v_grid').data('kendoGrid').dataItem($(this));
        codedString = codedString + dataItem.product_coded + ","
    })

    // 移除最后一个符号
    codedString = removeSuffix(codedString, ",");
    copyToClip(codedString);
    codedString.length > 0 ? msg("拷贝完毕！") : msg("拷贝了空白内容！")
}

// 获取表格选中的多行
function getSelectedRows() {
    return $('#v_grid').data('kendoGrid').select();
}

/**
 * 复制内容到粘贴板
 * content : 需要复制的内容
 * message : 复制完后的提示，不传则默认提示"复制成功"
 */
function copyToClip(content, message) {
    var aux = document.createElement("input");
    aux.setAttribute("value", content);
    document.body.appendChild(aux);
    aux.select();
    document.execCommand("copy");
    document.body.removeChild(aux);
    if (message == null) {
        // alert("复制成功");
    } else {
        alert(message);
    }
}

/**
 * 2021年7月4日 23:05:58
 * chanchaw
 * raw：传入原始字符串
 * suffix：字符串最后一个字符符合则删除后返回
 */
function removeSuffix(raw, suffix) {
    let str = raw.toString();
    let last = str.substr(str.length - 1, 1);
    if (last == suffix)
        str = str.substr(0, str.length - 1)
    return str;
}